﻿using InfonavaEye.components;
using InfonavaEye.model;
using InfonavaEye.model.wjapi;
using InfonavaEye.Service;

using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Windows.Forms;

namespace InfonavaEye.handler
{
    public class WuJingStroageService
    {
        public static WuJingStroageService instance = null;
        public static WuJingStroageService Instance {
            get
            {
                if (instance == null)
                {
                    instance = new WuJingStroageService();

                }
                return instance;
            }
        }

        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="path"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
      /*  public UploadFileResponse UploadFile(UploadFileParams file)
        {
            try
            {
                // 设置参数
                HttpWebRequest request = WebRequest.Create(WujingConfigService.StorageConfig.uploadFileUrl) as HttpWebRequest;
                CookieContainer cookieContainer = new CookieContainer();
                request.CookieContainer = cookieContainer;
                request.AllowAutoRedirect = true;
                request.Method = "POST";
                request.Timeout = 600000;
                string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
                request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
                byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
                byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");

                string fileName = Path.GetFileName(file.filePath);

                //请求头部信息 
                StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName));
                byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());

                FileStream fs = new FileStream(file.filePath, FileMode.Open, FileAccess.Read);
                //byte[] bArr = new byte[fs.Length];
               // fs.Read(bArr, 0, bArr.Length);
                //fs.Close();

                byte[] dataByte=new byte[4096];
                Stream postStream = request.GetRequestStream();
                postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
                postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
                //  postStream.Write(bArr, 0, bArr.Length);
                while (fs.Read(dataByte, 0, dataByte.Length)>0)
                {
                    postStream.Write(dataByte, 0, dataByte.Length);
                }
                postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
                fs.Close();
                postStream.Close();

                //发送请求并获取相应回应数据
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
              
                Stream instream = response.GetResponseStream();
                StreamReader sr = new StreamReader(instream, Encoding.UTF8);
                //返回结果
                string result = sr.ReadToEnd();
                Console.WriteLine("上传文件的结果===result：{0}",result);
                WuJingApiBaseDto<WujingFileUploadApiResponse> respResult = JsonConvert.DeserializeObject<WuJingApiBaseDto<WujingFileUploadApiResponse>>(result);

                UploadFileResponse responseUp = new UploadFileResponse()
                {
                    Success = false
                };
                if (respResult.code==200) {
                    responseUp.Success = true;
                    responseUp.ServerType = "wujing";
                    responseUp.ContentLength = 0;
                    WujingFileUploadApiResponse respData = respResult.data;
                    responseUp.FileUrl = respData.filePath;
                    responseUp.FileId = respData.id;
                }
                return responseUp;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed with error info: {0}", ex.Message);
            }
            return new UploadFileResponse()
            {
                Success = false,
            };
        }*/

        public UploadFileResponse UploadFile(UploadFileParams file) {
            HttpClient client = new HttpClient();
            var formData = new MultipartFormDataContent();
            StreamContent content = new StreamContent(new FileStream(@file.filePath,FileMode.Open,FileAccess.Read));
            content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/octet-stream");
            formData.Add(content,"file", Path.GetFileName(file.filePath));
            formData.Add(new StringContent(file.ScanSN),"scanSN");
            formData.Add(new StringContent(file.shape.ToString()), "imageShape");
            formData.Add(new StringContent(file.isLast.ToString()), "isEnd");
            HttpResponseMessage resp=client.PostAsync(
                 Eps.Ai.Common.Config.OCR_SERVICE_DOMAIN+ "/api/ocr/straightImg",
                formData).Result;
            string result = resp.Content.ReadAsStringAsync().Result;
            Console.WriteLine("上传文件的结果===result：{0}", result);
            WuJingApiBaseDto<WujingFileUploadApiResponse> respResult = JsonConvert.DeserializeObject<WuJingApiBaseDto<WujingFileUploadApiResponse>>(result);

            UploadFileResponse responseUp = new UploadFileResponse()
            {
                Success = false
            };
            if (respResult.code == 200)
            {
                responseUp.Success = true;
                responseUp.ServerType = "wujing";
                responseUp.ContentLength = 0;
                WujingFileUploadApiResponse respData = respResult.data;
                responseUp.FileUrl = respData.url;
                responseUp.FileId = respData.fileId;
            }
            return responseUp;
        }
    }
}
